package com.example.sihookuiklydemo

import com.example.myapplication.base.DeskHeightActionSheetEvent
import com.example.myapplication.base.DeviceNameActionSheetEvent
import com.example.myapplication.base.LanguageActionSheetEvent
import com.example.myapplication.base.LanguageActionSheetView
import com.example.myapplication.base.NavBar
import com.example.sihookuiklydemo.base.BasePager
import com.example.sihookuiklydemo.base.BridgeModule
import com.example.sihookuiklydemo.base.NotifyName
import com.example.sihookuiklydemo.base.NotifyName.Companion.DESK_MODE_LIST
import com.example.sihookuiklydemo.base.ProgressDialog
import com.example.sihookuiklydemo.base.ToastDialog
import com.example.sihookuiklydemo.bean.CustomDeskModeJson
import com.example.sihookuiklydemo.bean.DeskModeQuery
import com.example.sihookuiklydemo.bean.getDeskModeList
import com.example.sihookuiklydemo.ble.getNewFloatPx
import com.example.sihookuiklydemo.net.Api.Companion.baseUrl
import com.example.sihookuiklydemo.utils.feetInchesToCentimeters
import com.example.sihookuiklydemo.utils.getLanguage
import com.example.sihookuiklydemo.utils.getNetErrorText
import com.example.sihookuiklydemo.utils.getShowHeightString
import com.example.sihookuiklydemo.utils.toFeetInches
import com.tencent.kuikly.core.annotations.Page
import com.tencent.kuikly.core.base.Border
import com.tencent.kuikly.core.base.BorderStyle
import com.tencent.kuikly.core.base.Color
import com.tencent.kuikly.core.base.ViewBuilder
import com.tencent.kuikly.core.base.attr.ImageUri
import com.tencent.kuikly.core.directives.vfor
import com.tencent.kuikly.core.directives.vforIndex
import com.tencent.kuikly.core.directives.vif
import com.tencent.kuikly.core.log.KLog
import com.tencent.kuikly.core.manager.PagerManager
import com.tencent.kuikly.core.module.NetworkModule
import com.tencent.kuikly.core.module.NotifyModule
import com.tencent.kuikly.core.module.RouterModule
import com.tencent.kuikly.core.module.SharedPreferencesModule
import com.tencent.kuikly.core.nvi.serialization.json.JSON
import com.tencent.kuikly.core.nvi.serialization.json.JSONArray
import com.tencent.kuikly.core.nvi.serialization.json.JSONObject
import com.tencent.kuikly.core.reactive.handler.observable
import com.tencent.kuikly.core.reactive.handler.observableList
import com.tencent.kuikly.core.views.Image
import com.tencent.kuikly.core.views.List
import com.tencent.kuikly.core.views.Modal
import com.tencent.kuikly.core.views.RichText
import com.tencent.kuikly.core.views.Scroller
import com.tencent.kuikly.core.views.Text
import com.tencent.kuikly.core.views.View
import com.tencent.kuikly.core.views.compose.Button

@Page("ModeSetting")
internal class ModeSettingPage : BasePager() {
    private lateinit var titleArray: Array<String>
    var deskModeList by observableList<CustomDeskModeJson>()

    //模式内的高度位置
    var showDeskIndex by observable(-1)

    //模式位置
    var showDeskPosition by observable(-1)
    var currentValue by observable(0)
    var showNameIndex by observable(-1)
    var autoHeight = 210f
    var diyHeight = 160f
    var showProgressDialog by observable(false)
    var showMsgDialog by observable(false)
    var toastMsg by observable("")
    var heightUnit = 0
    override fun body(): ViewBuilder {
        val ctx = this
        return {
            NavBar {
                attr {
                    title = if (ctx.titleName.isNullOrEmpty()) "模式设置" else ctx.titleName!!
                    rightIconShow = false
                    isDarkMode = ctx.isNightMode()
                }
                event {
                    onClick {

                        ctx.acquireModule<RouterModule>(RouterModule.MODULE_NAME).closePage()

                    }

                }
            }
            attr {
                backgroundColor(ctx.theme.colors.background)
            }
            List {
                attr {
                    flex(1f)
                    marginBottom(120f)
                }
                vforIndex({ ctx.deskModeList }) { item, index, _ ->
                    View {
                        attr {

                            marginLeft(24f)
                            marginRight(24f)
                            marginTop(18f)
                            width(ctx.pagerData.pageViewWidth - 48f)
                        }
                        View {
                            attr {
                                flexDirectionRow()
                            }
                            Text {
                                attr {
                                    var showName = if (item.isAuto == true) getLanguage(
                                        "desk_auto_mode",
                                        "智能模式"
                                    ) else item.name

                                    color(ctx.theme.colors.mainTextColor)
                                    text(showName ?: "")
                                    useDpFontSizeDim(true)
                                    fontSize(17f)
                                }
                            }
                            vif({ item.isAuto == false }) {
                                Image {
                                    attr {
                                        size(20f, 20f)
                                        src(ImageUri.commonAssets("ic_ms.png"))
                                    }
                                    event {
                                        click {
                                            ctx.showNameIndex = index
                                        }
                                    }
                                }
                            }

                        }
                        Scroller {
                            attr {

                                scrollEnable(item.isAuto != true)
                                flexDirectionRow()

                                minHeight(if (item.isAuto == true) ctx.autoHeight else ctx.diyHeight)
                                // height(if (item.isAuto == true) ctx.autoHeight else ctx.diyHeight)
                                width(ctx.pagerData.pageViewWidth - 48f)
                            }
                            View {
                                attr {
                                    marginTop(4f)
                                    flexDirectionColumn()

                                    alignItemsStretch()
                                    width(ctx.pagerData.pageViewWidth - 48f)
                                    backgroundColor(ctx.theme.colors.grey_1a)
                                    borderRadius(20f)
                                    border(
                                        Border(
                                            1f,
                                            BorderStyle.SOLID,
                                            Color(0xffE0E2E7)
                                        )
                                    )


                                }
                                apply(ctx.tipsView(item))
                                View {
                                    attr {
                                        flexDirectionRow()
                                        alignItemsCenter()
                                        flex(1f)

                                        justifyContentSpaceEvenly()
                                    }
                                    View {
                                        attr {
                                            alignSelfCenter()
                                            marginTop(if (item.isAuto == true) 8f else 36f)

                                        }
                                        Image {
                                            attr {
                                                alignSelfCenter()
                                                size(60f, 60f)
                                                src(ImageUri.commonAssets("sittingposture_1.png"))
                                            }
                                        }
                                        Text {
                                            attr {
                                                color(0xff98A2AC)
                                                marginTop(4f)
                                                textAlignCenter()
                                                maxWidth(100f)
                                                marginBottom(16f)
                                                var showText = getShowHeightString(item.sit!!, ctx.heightUnit)
                                                text("${showText}")
                                                useDpFontSizeDim(true)
                                                alignSelfCenter()
                                            }
                                        }
                                        event {
                                            click {

                                                item.sit?.let {
                                                    this@ModeSettingPage.currentValue = it
                                                }
                                                if (item.isAuto == false) {
                                                    ctx.showDeskIndex = 0
                                                    ctx.showDeskPosition = index
                                                }

                                            }
                                        }
                                    }
                                    View {
                                        attr {
                                            marginTop(if (item.isAuto == true) 6f else 6f)
                                            backgroundColor(ctx.theme.colors.grey_2)
                                            size(1f, 60f)
                                        }
                                    }
                                    View {
                                        attr {
                                            alignSelfCenter()
                                        }
                                        Image {

                                            attr {
                                                alignSelfCenter()
                                                marginTop(if (item.isAuto == true) 8f else 36f)
                                                size(60f, 60f)
                                                src(ImageUri.commonAssets("sittingposture_2.png"))
                                            }
                                        }
                                        Text {
                                            attr {
                                                color(0xff98A2AC)
                                                marginTop(4f)
                                                marginBottom(16f)
                                                textAlignCenter()
                                                maxWidth(100f)
                                                var showText = getShowHeightString(
                                                    item.stand!!,
                                                    ctx.heightUnit
                                                )
                                                text("${showText}")
                                                alignSelfCenter()
                                                useDpFontSizeDim(true)
                                            }
                                        }
                                        event {
                                            click {

                                                item.stand?.let {
                                                    this@ModeSettingPage.currentValue = it
                                                }
                                                if (item.isAuto == false) {
                                                    ctx.showDeskIndex = 1
                                                    ctx.showDeskPosition = index
                                                }
                                            }
                                        }
                                    }
                                    View {
                                        attr {

                                            marginTop(if (item.isAuto == true) 0f else 6f)
                                            backgroundColor(ctx.theme.colors.grey_2)
                                            size(1f, 60f)
                                        }
                                    }
                                    View {
                                        attr {
                                            alignSelfCenter()
                                        }
                                        Image {

                                            attr {
                                                alignSelfCenter()
                                                marginTop(if (item.isAuto == true) 8f else 36f)
                                                size(60f, 60f)
                                                src(ImageUri.commonAssets("sittingposture_3.png"))
                                            }
                                        }
                                        Text {
                                            attr {
                                                marginTop(4f)
                                                marginBottom(16f)
                                                color(0xff98A2AC)
                                                textAlignCenter()
                                                maxWidth(100f)
                                                var showText = getShowHeightString(
                                                    item.custom!!,
                                                    ctx.heightUnit
                                                )
                                                marginBottom(16f)
                                                text("${showText}")
                                                alignSelfCenter()
                                                useDpFontSizeDim(true)
                                            }
                                        }
                                        event {
                                            click {
                                                item.custom?.let {
                                                    this@ModeSettingPage.currentValue = it
                                                }
                                                if (item.isAuto == false) {
                                                    ctx.showDeskIndex = 2
                                                    ctx.showDeskPosition = index
                                                }
                                            }
                                        }
                                    }

                                }


                            }

                            Button {
                                attr {
                                    backgroundColor(Color.RED)
                                    borderRadius(4f)
                                    marginLeft(16f)
                                    marginTop(12f)
                                    marginBottom(8f)
                                    alignSelfStretch()
                                    width(80f)


                                    titleAttr {
                                        text(getLanguage("health_history_delete", "删除"))
                                        useDpFontSizeDim(true)
                                        color(Color.WHITE)
                                    }
                                }
                                event {
                                    click {
                                        ctx.deleteDeskMode(index)
                                    }
                                }
                            }

                        }


                    }


                }
            }
            vif({ ctx.showDeskIndex != -1 }) {
                Modal {
                    DeskHeightActionSheetEvent {
                        attr {
                            title = ctx.titleArray[ctx.showDeskIndex]
                            currentValue = ctx.currentValue.toString()
                            val (feet, inches) = ctx.currentValue.toFeetInches()
                            chooseFtValue = feet.toString()
                            chooseInValue = inches.toString()
                            heightUnit = pagerData.params.optInt(NotifyName.HEIGHT_UNIT)
                        }
                        event {
                            onConfirmClick {
                                ctx.checkHeight(it.toInt())
                                KLog.i("close", it.toString())
                            }
                            onConfirmImClick { selectedFtValue, selectedInValue ->
                                var transSelectedValue = feetInchesToCentimeters(
                                    selectedFtValue.toInt(),
                                    selectedInValue.toInt()
                                )
                                ctx.checkHeight(transSelectedValue)
                                KLog.i("close", "$selectedFtValue ${selectedInValue}")
                            }
                            onCancelClick {
                                ctx.showDeskIndex = -1
                            }
                        }
                    }
                }
            }
            vif({ ctx.showNameIndex != -1 }) {
                Modal {
                    DeviceNameActionSheetEvent {
                        attr {
                            ctx.deskModeList[ctx.showNameIndex].name?.let {
                                deviceName = it
                                nameTag = ctx.getLanguage("desk_mode_name", "模式名")
                            }
                        }
                        event {
                            // onRightClick { ctx.showDeviceNameDialog = false }
                            onCancelClick {
                                ctx.showNameIndex = -1

                            }
                            onConfirmClick {
                                ctx.deskModeList[ctx.showNameIndex].name = it
                                ctx.deskModeList[ctx.showNameIndex] =
                                    ctx.deskModeList[ctx.showNameIndex]
                                ctx.showNameIndex = -1
                                ctx.updateDeskMode()
                                KLog.i("deviceName", "$it")
                            }
                        }
                    }
                }
            }

            Button {
                attr {
                    size(ctx.pagerData.pageViewWidth - 48f, getNewFloatPx(48f))
                    backgroundColor(Color.parseString16ToLong("0xffFF3D00"))
                    highlightBackgroundColor(Color(Color.parseString16ToLong("0xccFF3D00")))
                    titleAttr {
                        text(getLanguage("desk_add_mode", "新增"))
                        color(Color.WHITE)
                        useDpFontSizeDim(true)
                    }
                    positionAbsolute()
                    borderRadius(getNewFloatPx(24f))
                    left(24f)
                    right(24f)
                    bottom(44f)
                    highlightBackgroundColor(Color(Color.parseString16ToLong("0x644B4C4D")))

                }
                event {
                    click {
                        ctx.addDeskMode()
                    }
                }

                vif({ ctx.showProgressDialog }) {
                    Modal {
                        ProgressDialog { }
                    }
                }
                vif({ ctx.showMsgDialog }) {
                    Modal {
                        ToastDialog {
                            attr {
                                msg = ctx.toastMsg
                            }
                            event {
                                onDissMiss {
                                    ctx.showMsgDialog = false
                                }
                            }
                        }
                    }
                }
            }


        }
    }

    fun checkHeight(selectedValue: Int) {
        when (showDeskIndex) {
            0 -> {
                var standHeight =
                    deskModeList[showDeskPosition].stand
                if (standHeight!! < selectedValue) {
                    toastMsg = getLanguage(
                        "desk_mode_set_prompt1",
                        "设置的坐高不可超过站高"
                    )
                    showMsgDialog = true
                } else {
                    deskModeList[showDeskPosition].sit = selectedValue
                    updateDeskMode()
                }

            }

            1 -> {
                var sit = deskModeList[showDeskPosition].sit
                if (sit!! > selectedValue) {
                    toastMsg = getLanguage(
                        "desk_mode_set_prompt2",
                        "设置的站高不可小于坐高"
                    )
                    showMsgDialog = true
                } else {
                    deskModeList[showDeskPosition].stand =
                        selectedValue
                    updateDeskMode()
                }

            }

            2 -> {
                deskModeList[showDeskPosition].custom = selectedValue
                updateDeskMode()
            }
        }

        showDeskIndex = -1
    }

    fun tipsView(item: CustomDeskModeJson): ViewBuilder {
        return {
            vif({ item.isAuto }) {
                View {
                    attr {

                        minHeight(48f)
                        width(220f)

                        backgroundColor(Color.parseString16ToLong("0xffFF3D00"))
                        borderRadius(20f, 0f, 0f, 20f)
                    }
                    Text {
                        attr {
                            text(
                                getLanguage(
                                    "desk_auto_mode_tips",
                                    "西昊根据人体工程学数据为您推荐的专属高度"
                                )
                            )
                            margin(left = 12f, right = 8f, top = 8f, bottom = 8f)
                            fontSize(getNewFloatPx(15f))
                            useDpFontSizeDim(true)
                            color(Color.WHITE)
                        }

                    }
                }
            }
        }
    }

    override fun created() {
        super.created()
        titleArray = arrayOf(
            getLanguage("desk_set_sitting_height", "设置坐姿高度"),
            getLanguage("desk_set_sitting_height", "设置站姿高度"),
            getLanguage("desk_set_sitting_height", "设置自定义高度")
        )
        var deskModeListString =
            acquireModule<SharedPreferencesModule>(SharedPreferencesModule.MODULE_NAME)
                .getObject("DeskModeList")
        deskModeListString?.let {
            deskModeList.clear()
            deskModeList.addAll(getDeskModeList(deskModeListString))
        }
        defalutModeName = arrayOf(
            getLanguage("desk_mode1", "模式一"),
            getLanguage("desk_mode2", "模式二"),
            getLanguage("desk_mode3", "模式三"),
            getLanguage("desk_mode4", "模式四")
        )
        heightUnit = pagerData.params.optInt(NotifyName.HEIGHT_UNIT)
        queryDeskModeList()
    }

    fun queryDeskModeList(needLocalRefresh: Boolean = false) {
        var pageJson = pagerData.params

        pageJson?.let {
            var token = it.optString("token")
            var userId = it.optInt("userId")
            var eqId = it.optInt("equipmentId")
            var jsonObject = JSONObject()
            jsonObject.put("equipmentId", eqId)
            jsonObject.put("token", token)
            jsonObject.put("userId", userId)
            var jsonObjectHeader = JSONObject()
            jsonObjectHeader.put("Content-Type", "application/json")
            acquireModule<NetworkModule>(NetworkModule.MODULE_NAME).httpRequest(
                "${baseUrl}app/equipment/info/query",
                true,
                jsonObject,
                headers = jsonObjectHeader,
                responseCallback = { data, success, errorMsg, networkResponse ->
                    var content = data.optJSONObject("content")
                    var code = data.optInt("code")
                    var statusCode = networkResponse.statusCode
                    showProgressDialog = false
                    if (statusCode == 200) {
                        if (code == 0) {
                            content?.let {
                                KLog.i("模式设置页content", "queryDeskModeList:$it ")
                                val bridgeModule =
                                    PagerManager.getCurrentPager()
                                        .getModule<BridgeModule>(BridgeModule.MODULE_NAME)
                                bridgeModule?.sendNotify(DESK_MODE_LIST, data)
                                deskModeList.clear()
                                deskModeList.addAll(getDeskModeList(it))

                            }
                            /*  toastMsg="更新模式成功"
                              showMsgDialog=true*/
                        }
                    } else {
                        toastMsg = getNetErrorText()
                        showMsgDialog = true
                    }



                    KLog.i("ss", "${data.toString()} $success $errorMsg $networkResponse")
                })
        }
    }


    fun deleteDeskMode(position: Int) {
        var tempList = ArrayList<CustomDeskModeJson>()
        deskModeList.filterIndexed { index, customDeskModeJson -> index != position }.forEach {
            tempList.add(it)
        }
        var customDeskModeJson = deskModeList[position]
        updateDeskMode(tempList, customDeskModeJson.name)
    }

    var defalutModeName = arrayOf("模式一", "模式二", "模式三", "模式四")
    fun addDeskMode() {
        var modeSize = deskModeList.size
        if (modeSize >= 5) {
            toastMsg = getLanguage("desk_mode_length_limit", "支持添加4个自定义模式，当前已达上限")
            showMsgDialog = true
            return
        }
        var autoMode = deskModeList[0]
        autoMode?.let {
            var deskMode = CustomDeskModeJson()
            deskMode.custom = autoMode.custom
            deskMode.sit = autoMode.sit
            deskMode.stand = autoMode.stand
            deskMode.isAuto = false
            deskMode.isSelected = false
            deskMode.name = defalutModeName[deskModeList.size - 1]
            var tempList = ArrayList<CustomDeskModeJson>()
            deskModeList.forEach {
                tempList.add(it)
            }
            tempList.add(deskMode)

            updateDeskMode(tempList)
        }


    }

    fun updateDeskMode(
        modeList: ArrayList<CustomDeskModeJson>? = null,
        deleteName: String? = null
    ) {
        showProgressDialog = true
        var pageJson = pagerData.params
        pageJson?.let {

            var token = it.optString("token")
            var userId = it.optInt("userId")
            var eqId = it.optInt("equipmentId")
            var jsonObject = JSONObject()
            jsonObject.put("equipmentId", eqId)
            jsonObject.put("token", token)
            jsonObject.put("userId", userId)
            var uploadList = modeList ?: deskModeList
            //之前选中的模式删除之后把智能模式选中
            var selectedModeList = uploadList.filter { it.isSelected == true }

            var jsonArray = JSONArray()
            uploadList.forEach {
                var jsonChild = JSONObject()
                jsonChild.put("custom", it.custom)
                jsonChild.put("isAuto", it.isAuto)
                jsonChild.put(
                    "isSelected",
                    if (selectedModeList.isNullOrEmpty()) it.isAuto else it.isSelected
                )
                jsonChild.put("name", it.name)
                jsonChild.put("sit", it.sit)
                jsonChild.put("stand", it.stand)
                jsonArray.put(jsonChild)
            }

            jsonObject.put("customDeskModeJson", jsonArray)
            // jsonObject.put("customDeskModeJson",)
            var jsonObjectHeader = JSONObject()
            jsonObjectHeader.put("Content-Type", "application/json")
            acquireModule<NetworkModule>(NetworkModule.MODULE_NAME).httpRequest(
                "${baseUrl}app/equipment/electricDesk/updateConfig",
                true,
                jsonObject,
                headers = jsonObjectHeader,
                responseCallback = { data, success, errorMsg, networkResponse ->

                    var content = data.optJSONObject("content")

                    var statusCode = networkResponse.statusCode
                    //statusCode=200时说明网络通讯正常
                    //data.optInt会有默认值0返回
                    if (statusCode == 200) {
                        var code = data.optInt("code")
                        if (code == 0) {
                            if (selectedModeList.isNullOrEmpty()) {
                                deleteName?.let {
                                    getFormatLanguage("desk_mode_delete_auto", it)?.let {
                                        toastMsg = it
                                        showMsgDialog = true
                                    }

                                }

                            }
                            queryDeskModeList()
                        } else {
                            showProgressDialog = false
                        }
                    } else {
                        showProgressDialog = false
                        toastMsg = getNetErrorText()
                        showMsgDialog = true
                    }


                    KLog.i("content", "updateDeskMode:$it ${errorMsg} ${networkResponse}")

                })
        }
    }


}


